<template>
	<Page>
		<Topbar hideMenu />
		<Content>
			<Panel style="padding: 0 4rem;">
				<view class="tab-demo">
					<Tabs :data="tabs" v-model="active" @click="tabClick">
						<view class="back" @click="back" slot="toolbar">
							<u-icon name="arrow-left" color="#666" size="14" style="margin-right: 0.5rem;"></u-icon>
							返回
						</view>
					</Tabs>
					<FormWrap v-if="active.value ==='停机操作' && device.abnormalStatus === '未停机设备'">
						<u--form :labelPosition="labelPosition" :model="model" :rules="rules" ref="uForm"
							labelWidth="16rem" :labelStyle="{'margin-bottom' : labelPosition === 'top' ? '2rem' : '0'}"
							style="margin-top: 2rem; padding: 0 5rem;">
							<u-form-item label="设备编号">
								{{ device.deviceNo || '--' }}
							</u-form-item>
							<u-form-item label="停机类别" prop="shutdownCategory">
								<u-radio-group v-model="model.shutdownCategory" placement="row" @change="change">
									<u-radio v-for="(item, index) in shutdownCategorys" :key="index" :label="item.label"
										:name="item.value">
									</u-radio>
								</u-radio-group>
							</u-form-item>
							<u-form-item label="停机原因" prop="reasonShutdown">
								<u-radio-group v-model="model.reasonShutdown" placement="row">
									<u-radio v-for="(item, index) in reasonShutdowns" :key="index" :label="item.label"
										:name="item.value">
									</u-radio>
								</u-radio-group>
							</u-form-item>
							<u-form-item label="班次" prop="shift" class="label-fwn">
								<SingleSelect v-model="model.shift" :list="shifts" mode="single" />
							</u-form-item>
							<u-form-item label="备注">
								<InputField v-model="model.remarks" :maxlength="100" />
							</u-form-item>
						</u--form>
						<template slot="footer">
							<Button large type="primary" @click="open1">
								停机开始
							</Button>
						</template>
					</FormWrap>
					<FormWrap v-if="active.value ==='停机操作' && device.abnormalStatus === '停机设备'">
						<u--form :labelPosition="labelPosition" :model="model" labelWidth="16rem"
							:labelStyle="{'margin-bottom' : labelPosition === 'top' ? '2rem' : '0'}" style="
                                margin-top: 2rem; padding: 0 5rem;">
							<u-form-item label="停机开始时间">
								{{ deviceStatus.shutdownStartTime || '--' }}
							</u-form-item>
							<u-form-item label="停机类别">
								{{ deviceStatus.shutdownCategory || '--' }}
							</u-form-item>
							<u-form-item label="停机原因">
								{{ deviceStatus.reasonShutdown || '--' }}
							</u-form-item>
							<u-form-item label="操作人">
								{{ deviceStatus.operator  || '--' }}
							</u-form-item>
							<u-form-item label="备注">
								<InputField v-model="model.remarks" :maxlength="100" />
							</u-form-item>
						</u--form>
						<template slot="footer">
							<Button type="primary" large @click="open2">
								停机结束
							</Button>
						</template>
					</FormWrap>
					<view class="list" v-if="active.value ==='停机历史列表'">
						<view class="row" v-for="(item, index) in list" :key="index">
							<view class="col">
								<view class="index">
									{{index+1}}
								</view>
								<view class="text">
									停机时长：{{ item.shutdownDuration }}
								</view>
							</view>
							<view class="col">
								<view class="text">
									停机原因：{{ item.reasonShutdown }}
								</view>
							</view>
							<view class="col">
								<view class="text">
									停机类别：{{ item.shutdownCategory }}
								</view>
							</view>
							<view class="col">
								<view class="text">
									{{ item.shutdownStartTime }} - {{ item.shutdownEndTime }}
								</view>
							</view>
						</view>
					</view>
				</view>
			</Panel>
		</Content>
		<Modal title="确认开始停机吗？" ref="popup1" @confirm="confirm1" />
		<Modal title="确认结束停机吗？" ref="popup2" @confirm="confirm2" />
	</Page>
</template>

<script>
	import Page from "@/components/page/index.vue";
	import Topbar from "@/components/topbar/index.vue";
	import Content from "@/components/content/index.vue";
	import Panel from "@/components/panel/index.vue";
	import Empty from "@/components/empty/index.vue";
	import Button from "@/components/button/index.vue";
	import Tabs from "@/components/tabs/index";
	import FormWrap from '@/components/formWrap/index.vue';
	import InputField from '@/components/formField/inputField/index.vue';
	import Modal from '@/components/modal/index.vue';
	import fetch from "@/utils/fetch";
	import SingleSelect from '@/components/formField/singleSelect/index.vue';
	import {
		timeIsBetweenTimeRange
	} from "@/utils/date";
	import {
		getUserInfo,
		getDevice
	} from "@/store/user.js";
	import filter from "@/utils/filter";
	export default {
		components: {
			Page,
			Topbar,
			Content,
			Panel,
			Empty,
			SingleSelect,
			Button,
			Tabs,
			FormWrap,
			InputField,
			Modal
		},
		data() {
			return {
				active: {
					label: '停机操作',
					value: '停机操作'
				},
				shifts: [],
				labelPosition: 'left',
				device: getDevice(),
				deviceStatus: {},
				tabs: [{
						label: '停机操作',
						value: '停机操作'
					},
					{
						label: '停机历史列表',
						value: '停机历史列表'
					}
				],
				shutdownCategorys: [],
				reasonShutdowns: [],
				model: {
					shutdownCategory: '',
					reasonShutdown: '',
					shift: null,
				},
				rules: {
					'shutdownCategory': {
						type: 'number',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
					'reasonShutdown': {
						type: 'string',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
				},
				list: []
			};
		},
		onLoad() {
			this.getShiftList();
		},
		methods: {
			getShiftList() {
				console.log(getDevice().deviceNo, this.dayjs(this.model.shiftTime).format('YYYY-MM-DD'));
				fetch("get", "/dms/mobile/getShiftList", {
					deviceNo: getDevice().deviceNo,
					shiftDate: this.dayjs(this.model.shiftTime).format('YYYY-MM-DD'),
				}).then((res) => {
					this.shifts = res.map((item) => ({
						label: item.shift,
						value: item.shiftId,
						...item
					}));
					if (this.shifts.length !== 0) {
						// 获取当前时间（小时和分钟）
						const now = new Date();
						const currentHours = now.getHours();
						const currentMinutes = now.getMinutes();
						const currentTimeInMinutes = currentHours * 60 + currentMinutes;

						// 判断时间是否在班次范围内（处理跨天情况，如晚班）
						function isTimeInShift(startTime, endTime) {
							const [startHour, startMinute] = startTime.split(':').map(Number);
							const [endHour, endMinute] = endTime.split(':').map(Number);

							const startTotalMinutes = startHour * 60 + startMinute;
							const endTotalMinutes = endHour * 60 + endMinute;

							if (startTotalMinutes < endTotalMinutes) {
								// 不跨天的情况（如白班：07:30-18:00）
								return currentTimeInMinutes >= startTotalMinutes && currentTimeInMinutes <
									endTotalMinutes;
							} else {
								// 跨天的情况（如晚班：18:00-07:30）
								return currentTimeInMinutes >= startTotalMinutes || currentTimeInMinutes <
									endTotalMinutes;
							}
						}

						// 查找符合条件的班次
						let selectedSchedule = null;
						for (const schedule of this.shifts) {
							if (isTimeInShift(schedule.shiftStartTime, schedule.shiftEndTime)) {
								selectedSchedule = schedule;
								break; // 选择第一个符合条件的班次
							}
						}

						// 如果没有符合条件的班次，默认选择第一项
						if (!selectedSchedule) {
							selectedSchedule = this.shifts[0];
						}

						// 打印结果
						console.log("选中的班次：", selectedSchedule);
							this.model.shift = selectedSchedule.value
						// const has = res.find(item => timeIsBetweenTimeRange(filter.formatCurrentTimeDuration(),
						// 	item.shiftStartTime,
						// 	item.shiftEndTime));
						// if (has)
						// 	this.model.shift = has.shift;
						// else
						// 	this.model.shift = this.shifts[0].value;

					} else {
						this.model.shift = null;
					}
				});
			},
			back() {
				this.goto('/pages/workbench/index');
			},
			tabClick(item) {
				if (item.value === '停机历史列表') {
					fetch('get', '/dms/mobile/getHistory', {
						deviceNo: this.device.deviceNo,
						pageNum: 1,
						pageSize: 999,
						timeRange: 'last30days',
					}).then((res) => {
						this.list = res.records;
					});
				}
			},
			open1() {
				this.$refs['uForm'].validate().then((valid) => {
					if (valid) {
						this.$refs.popup1.open()
					}
				});
			},
			open2() {
				this.$refs.popup2.open()
			},
			confirm1() {
				const shutdownCategory = this.shutdownCategorys.find(item => item.value === this.model.shutdownCategory)
					.label;
				fetch('post', '/dms/mobile/addAbnormal', null, {
					deviceNo: this.device.deviceNo,
					reasonShutdown: this.model.reasonShutdown,
					shutdownCategory,
					userName: getUserInfo().realname,
					remarks: this.model.remarks,
				}).then((res) => {
					this.$toast('异常停机成功');
					this.model.remarks = '';
					this.model.shutdownCategory = '';
					this.model.reasonShutdown = '';
					this.getDeviceFromRemote();
				});
			},
			confirm2() {
				fetch('post', '/dms/mobile/updateAbnormal', null, {
					deviceNo: this.device.deviceNo,
					userName: getUserInfo().realname,
					remarks: this.model.remarks,
				}).then((res) => {
					this.$toast('异常停机结束成功');
					this.model.remarks = '';
					this.model.shutdownCategory = '';
					this.model.reasonShutdown = '';
					this.getDeviceFromRemote();
				});
			},
			getDeviceFromRemote() {
				fetch('get', '/dms/mobile/getAbnormalShutdownStatus', {
					deviceNo: this.device.deviceNo,
				}).then((res) => {
					this.device = res;
					this.getDeviceAbnormalStatus();
					this.getDictData1();
				});
			},
			getDeviceAbnormalStatus() {
				fetch('get', '/dms/mobile/findAll', {
					deviceNo: this.device.deviceNo,
				}).then((res) => {
					this.deviceStatus = res;
				});
			},
			getDictData1() {
				fetch("get", "/dms/shutdownCategory/getShutdownCategoryList", {
					pageNum: 1,
					pageSize: 50,
				}).then((res) => {
					this.shutdownCategorys = res.records.map((item) => ({
						label: item.shutdownCategory,
						value: item.id,
					}));
					if (this.shutdownCategorys.length !== 0) {
						this.model.shutdownCategory = this.shutdownCategorys[0].value;
						this.getDictData2();
					}
				});
			},
			getDictData2() {
				fetch("get", "/dms/shutdownReason/getShutdownReasonList", {
					pageNum: 1,
					pageSize: 50,
					abnormalId: this.model.shutdownCategory,
				}).then((res) => {
					this.reasonShutdowns = res.records.map((item) => ({
						label: item.reasonForShutdown,
						value: item.reasonForShutdown,
					}));
				});
			},
			change() {
				this.model.reasonShutdown = null
				this.getDictData2();
			},
			goto(url) {
				uni.navigateTo({
					url,
					animationType: "pop-in",
					animationDuration: 1000,
				})
			},
		},
		mounted() {
			this.getDeviceFromRemote();
		}
	}
</script>

<style scoped lang="scss">
	.tab-demo {
		flex: 1;
		width: 100%;
	}

	.back {
		display: flex;
		justify-content: center;
		align-items: center;
		color: #666;
	}

	.list {
		padding: 3rem;

		.row {
			display: flex;
			justify-content: space-between;
			border: 1px solid #2f6da0;
			padding: 3rem;
			border-radius: 2rem;
			margin-bottom: 2rem;
			background-color: rgb(245, 248, 253);
			border-color: rgb(227, 236, 254);

			.col {
				display: flex;
				justify-content: flex-start;
				align-items: center;

				.index {
					border-radius: 5rem;
					background: #6b93cf;
					color: #fff;
					width: 4rem;
					height: 4rem;
					display: flex;
					justify-content: center;
					align-items: center;
					margin-right: 2rem;
				}

				.button-1 {
					background: #62c3f2;
					color: #fff;
				}
			}
		}
	}
</style>